package com.doudizu.shoesonline.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.doudizu.shoesonline.common.BaseResponse;
import com.doudizu.shoesonline.common.ResultUtils;
import com.doudizu.shoesonline.model.entity.Link;
import com.doudizu.shoesonline.service.LinkService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author ln
 */
@RestController
@RequestMapping("/link")
@Api(tags = "链接模块")
public class LinkController {
    @Resource
    private LinkService linkService;

    /**
     *  查询所有的链接
     * @return 保存链接信息的集合
     */
    @GetMapping("/list")
    @ApiOperation("查看所有链接")
    public BaseResponse<List<Link>> list() {
        List<Link> list = linkService.list();
        return ResultUtils.success(list);
    }

    /**
     *  分页查询
     * @param pageNum 页号
     * @param pageSize 页面展示的数据
     * @return 分页信息
     */
    @GetMapping("/page")
    @ApiOperation("链接分页查询")
    public BaseResponse<Page> page(int pageNum, int pageSize){
        Page pageInfo=new Page(pageNum,pageSize);
        LambdaQueryWrapper<Link> lambdaQueryWrapper=new LambdaQueryWrapper();
        lambdaQueryWrapper.orderByDesc(Link::getUpdateTime);
        Page page = linkService.page(pageInfo, lambdaQueryWrapper);
        return ResultUtils.success(page);
    }

    /**
     * 搜索友情链接
     * @param keyWord
     * @return
     */
    @GetMapping("/select")
    @ApiOperation("搜索友情链接")//模糊搜索
    public BaseResponse select(String keyWord){
        if (StringUtils.isBlank(keyWord)) {
            return this.list();
        }
        QueryWrapper<Link> queryWrapper = new QueryWrapper<>();
        queryWrapper.like("link_name",keyWord)
                .or().like("url",keyWord)
                .or().like("end_time",keyWord)
                .eq("type",0);
        List<Link> links = linkService.list(queryWrapper);
        return ResultUtils.success(links);
    }

    @PostMapping("/add")
    @ApiOperation("增加链接")
    public BaseResponse<String> save(@RequestBody Link link){
        linkService.save(link);
        return ResultUtils.success("增加链接名称和URL成功");
    }

    @PostMapping("/delete")
    @ApiOperation("单个或者批量删除链接信息")
    public BaseResponse delete(@RequestParam List<Integer> ids) {
        linkService.removeBatchByIds(ids);
        return ResultUtils.success(null);
    }

    @PostMapping("/update")
    @ApiOperation("修改链接信息")
    public BaseResponse update(@RequestBody Link link) {
        linkService.updateById(link);
        return ResultUtils.success(null);
    }


}
